//
//  HMTextView.swift
//  Weibo
//
//  Created by itteacher on 2017/7/31.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
//  自定义TextView
class HMTextView: UITextView {

    //  MARK: --    懒加载控件
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "请输入微博内容"
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = UIColor.lightGray
        //  多行显示
        label.numberOfLines = 0
        return label
    }()
    
    //  设置占位文字
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    //  设置字体大小的时候让占位文字与其同步
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        
        //  监听文字改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        //  添加约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }

    //  MARK: --   监听文字改变处理
    @objc private func textChange() {
        placeHolderLabel.isHidden = self.hasText
    }
    
    deinit {
        //  移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
   
 
}
